package cn.kickegg.design.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author KickEGG
 * @createTime 2018-08-02 22:00
 * @Description 验证单例模式是否可以被破坏
 */
public class ElvisReflectAttack {
  public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
  {
    Class<?> classType = LazySingleInstance.class;

    // 通过反射,使用构造器实现类的实例化,打到攻击目的
    Constructor<?> c = classType.getDeclaredConstructor(null);
    c.setAccessible(true);
    LazySingleInstance e1 = (LazySingleInstance)c.newInstance();
    LazySingleInstance e2 = LazySingleInstance.getInstance();
    System.out.println(e1==e2);// result:fasle
  }
}
